import { isWeixin } from "@/utils/channel";
import wechatOa from "@/utils/wechat";
import useUserStore from "@/stores/user";
import { wxApLogin } from "@/api/login";
import { ChannelEnum } from "@/enums/channelEnum";

export function useLogin() {
    /**
     * 三方登录
     */
    const oauth = (code: string | null) => {
        const userStore = useUserStore();

        // #ifdef MP-WEIXIN
        wxApLogin({ code: code, channel: ChannelEnum.WX_AP }).then((res:AnyObject) => {
            userStore.login(res.token);
        });
        // #endif

        // #ifdef H5
        if (isWeixin) {
            wechatOa.authLogin(code).then((res:AnyObject) => {
                userStore.login(res.token);
            })
        }
        // #endif

    };

    /**
     * 获取授权code
     * @param url 
     */
    const getCode = (url = '') => {
        // #ifdef MP-WEIXIN
        wx.login({
            success(res) {
                if (res.code) {
                    oauth(res.code);
                } else {
                    console.log("登录失败！" + res.errMsg);
                }
            },
        });
        // #endif

        // #ifdef H5
        if (isWeixin) wechatOa.authCodeUrl(url);
        // #endif
    };

    return {
        oauth,
        getCode,
    };
}
